/**
 * 文件历史记录服务
 * 使用dataPreferences实现文件操作历史记录的存储和管理
 */
import dataPreferences from '@ohos.data.preferences';
import { BusinessError } from '@ohos.base';

/**
 * 最大历史记录数量
 */
const MAX_HISTORY_ITEMS = 10;

/**
 * 首选项存储名称
 */
const PREFERENCES_NAME = 'fileHistoryPrefs';

/**
 * 历史记录存储键名
 */
const HISTORY_KEY = 'fileHistory';

/**
 * 历史记录服务类
 * 单例模式实现，提供文件操作历史记录的增删查功能
 */
class HistoryService {
  private static instance: HistoryService;
  private preferences: dataPreferences.Preferences | null = null;

  private constructor() {}

  /**
   * 获取历史服务单例实例
   * @async
   * @returns {Promise<HistoryService>} 历史服务实例
   */
  public static async getInstance(): Promise<HistoryService> {
    if (!HistoryService.instance) {
      HistoryService.instance = new HistoryService();
      await HistoryService.instance.initPreferences();
    }
    return HistoryService.instance;
  }

  private async initPreferences(): Promise<void> {
    try {
      this.preferences = await dataPreferences.getPreferences(globalThis.context, PREFERENCES_NAME);
    } catch (err) {
      console.error(`Failed to init preferences: ${JSON.stringify(err)}`);
      throw err;
    }
  }

  /**
   * 添加文件路径到历史记录
   * @async
   * @param {string} filePath - 要添加的文件路径
   * @returns {Promise<void>}
   * @throws {BusinessError} 当操作失败时抛出异常
   */
  public async addToHistory(filePath: string): Promise<void> {
    if (!filePath || typeof filePath !== 'string') {
      return;
    }

    try {
      const currentHistory = await this.getHistory();

      // Remove duplicate if exists
      const newHistory = currentHistory.filter(path => path !== filePath);

      // Add to beginning of array
      newHistory.unshift(filePath);

      // Limit max items
      if (newHistory.length > MAX_HISTORY_ITEMS) {
        newHistory.length = MAX_HISTORY_ITEMS;
      }

      await this.preferences?.put(HISTORY_KEY, JSON.stringify(newHistory));
      await this.preferences?.flush();
    } catch (err) {
      console.error(`Failed to add to history: ${JSON.stringify(err)}`);
      throw err;
    }
  }

  /**
   * 获取历史记录列表
   * @async
   * @returns {Promise<Array<string>>} 文件路径历史记录数组
   * @throws {BusinessError} 当操作失败时返回空数组
   */
  public async getHistory(): Promise<Array<string>> {
    try {
      const historyJson = await this.preferences?.get(HISTORY_KEY, '[]');
      return JSON.parse(historyJson as string) || [];
    } catch (err) {
      console.error(`Failed to get history: ${JSON.stringify(err)}`);
      return [];
    }
  }

  /**
   * 清空历史记录
   * @async
   * @returns {Promise<void>}
   * @throws {BusinessError} 当操作失败时抛出异常
   */
  public async clearHistory(): Promise<void> {
    try {
      await this.preferences?.delete(HISTORY_KEY);
      await this.preferences?.flush();
    } catch (err) {
      console.error(`Failed to clear history: ${JSON.stringify(err)}`);
      throw err;
    }
  }
}

export default HistoryService;
